<!-- 系统内容编辑页面 -->
<template>
  <div class="system-content-item" v-loading="globalLoading">
    <el-form ref="faqForm" :model="faq" label-width="100px" :rules="rules" v-loading="formLoading">
      <el-form-item label="FAQ标题" prop="title" class="width-limit">
        <el-input v-model="faq.title" size="medium" placeholder="输入不能超过200个字符" maxlength="200"></el-input>
      </el-form-item>

      <el-form-item label="FAQ分类" v-if="system && system.systemType && system.systemType.id === 6" class="width-limit">
        <el-select v-model="faq.categoryId" placeholder="请选择" size="medium" style="width:100%;">
          <el-option label="未分类" :value="-1">
          </el-option>
          <template v-for="item in categories[0]">
            <el-option :key="item.id" :label="item.name" :value="item.id"></el-option>
            <template v-for="ite in categories[item.id]">
              <el-option style="padding-left:36px;" :key="ite.id" :label="ite.name" :value="ite.id"></el-option>
              <template v-for="it in categories[ite.id]">
                <el-option style="padding-left: 54px;" :key="it.id" :label="it.name" :value="it.id"></el-option>
              </template>
            </template>
          </template>
        </el-select>
      </el-form-item>

      <el-form-item label="发布时间" class="width-limit">
        <el-date-picker v-model="faq.releasedAt" v-datetime-format type="datetime" placeholder="请选择发布时间" size="medium"
          style="width:100%;">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="是否显示" style="margin-top:-5px; margin-bottom:10px;">
        <el-switch v-model="faq.isShow" active-color="#13ce66">
        </el-switch>
      </el-form-item>

      <!-- <el-form-item label="是否置顶" style="margin-top:-5px; margin-bottom:10px;">
        <el-switch v-model="faq.isTop" active-color="#13ce66">
        </el-switch>
      </el-form-item> -->

      <el-form-item label="详细内容">
        <Ue :defaultValue="faq.info ? faq.info: ''" :contentChange="contentChange" :id="'content'" ref="content"></Ue>
      </el-form-item>

      <el-form-item class="footfixed">
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button type="success" @click="onSubmitAndGoSystemList">保存并返回系统列表</el-button>
        <el-button @click="goSystemList">返回系统列表</el-button>
      </el-form-item>
    </el-form>
    <!-- 分类级别树形结构显示 -->
    <TreeDialog :data="categoryTreeDialog" ref="categoryTreeDialog" title="分类级别树形结构显示" />
  </div>
</template>

<script>
import Ue from '@/components/common/ueditor/Ue.vue'
import TreeDialog from '@/components/common/dialog/TreeDialog.vue'
import * as functions from '@/core/functions.js'
export default {
  created () {
    let query = this.$route.query
    if (!query || !query.sid || !query.id) {
      this.$message.error('未能获取到正确的数据')
      return
    }
    let systemId = query.sid
    let id = query.id
    // 获取系统信息
    this.$post('/system/info', { id: systemId }).then((resoponse) => {
      if (resoponse && resoponse.id) {
        this.system = resoponse
        this.faq.systemId = this.system.id
        if (this.system.systemType && this.system.systemType.id === 6) {
          // 获取所有的分类信息
          this.$post('/category/table-data-infos-by-system-id', { systemId: systemId }).then((resoponse) => {
            if (resoponse.categories) {
              this.categories = resoponse.categories
            } else {
              this.categories = []
            }
            if (resoponse.categoryIds && resoponse.categoryIds.length > 0) {
              this.faq.categoryId = resoponse.categoryIds[0]
            }
            this.initComplete.categories = true
          })
        } else {
          // 不需要获取分类信息
          this.initComplete.categories = true
        }
      }
      this.initComplete.system = true
    })

    // 获取内容信息
    if (id > 0) {
      // 修改
      this.$post('/system/faq/info', { faqId: id }).then(response => {
        let faq = response
        if (faq) {
          this.faq = initFaq(faq, this)
          this.$refs['content'].setUEContent(this.faq.info ? this.faq.info : '')
        }
        this.initComplete.data = true
      })
    } else {
      // 新增
      this.initComplete.data = true
    }
  },
  data () {
    return {
      // 全局加载中
      globalLoading: true,
      // 表单加载
      formLoading: false,
      // 判断是否加载完成的三个加载项目
      initComplete: {
        categories: false,
        system: false,
        data: false
      },
      // 获取系统的分类信息
      categories: [],
      // 当前的系统
      system: {},
      // 当前content的数据
      data: {},
      // 表单数据
      faq: {
        categoryId: -1,
        config: '',
        id: 0,
        info: '',
        isShow: true,
        orderNum: 0,
        releasedAt: new Date(),
        rewrite: '',
        systemId: 0,
        title: ''
      },
      // 提交的表单规则
      rules: {
        title: [
          { required: true, message: '请输入标题名称', trigger: 'blur' },
          { max: 200, message: '不得超过200个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    categoryTreeDialog () {
      let result = getCategoryTreeData(this.categories, 0)
      return result
    }
  },
  watch: {
    initComplete: {
      handler (newVal) {
        this.$nextTick(() => {
          if (newVal.categories && newVal.system && newVal.data) {
            // 初始化请求完毕
            this.globalLoading = false
          }
        })
      },
      deep: true
    }
  },
  methods: {
    // 保存
    onSubmit (callback) {
      this.$refs['faqForm'].validate((valid) => {
        if (valid) {
          this.faq.info = this.$refs['content'].getUEContent()
          this.faq.isShow = this.faq.isShow ? 1 : 0
          this.formLoading = true
          this.$jpost('/system/faq/save', this.faq).then(response => {
            if (response) {
              let faq = response
              if (typeof callback === 'function') {
                callback()
              }
              this.faq = initFaq(faq, this)
            } else {
              console.error(response)
            }
            this.formLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 保存并返回系统列表
    onSubmitAndGoSystemList () {
      this.onSubmit(() => {
        this.goSystemList()
      })
    },
    // 返回系统列表
    goSystemList () {
      let fullPath = functions.getSystemListPathByItem(this.system)
      if (!fullPath) {
        return
      }

      // 存储系统页面页码，如果从编辑页返回列表页fromItem改为true
      let systbPageCur = JSON.parse(sessionStorage.getItem('systbPageCur' + this.system.id))
      if (systbPageCur) {
        systbPageCur.fromItem = true
        sessionStorage.setItem('systbPageCur' + this.system.id, JSON.stringify(systbPageCur))
      }

      this.$store.dispatch('navAppendAndClose', { path: fullPath, close: this.$route.fullPath })
    },
    // 当内容变化的时候
    contentChange (content) {
      this.faq.info = content
    },
    // 点击显示分类树形结构弹窗
    categoryTreeShow () {
      this.$refs['categoryTreeDialog'].show()
    }
  },
  components: {
    Ue,
    TreeDialog
  }
}

function getCategoryTreeData (data, key) {
  if (data.length < 1) {
    return []
  }
  let result = []
  for (let i in data[key]) {
    let item = data[key][i]
    let children
    if (data.hasOwnProperty(item.id)) {
      children = getCategoryTreeData(data, item.id)
    }
    let element = {}
    element.label = item.name
    if (children) {
      element.children = children
    }
    result.push(element)
  }
  return result
}

function initFaq (faq, vm) {
  let categoryId = -1
  if (faq.categoryQuote && faq.categoryQuote.scategories) {
    categoryId = faq.categoryQuote.scategories.id
  }
  let sfaq = faq.sfaq
  return {
    categoryId: categoryId,
    config: sfaq.config,
    id: sfaq.id,
    info: sfaq.info,
    isShow: sfaq.isShow > 0,
    orderNum: sfaq.orderNum,
    releasedAt: new Date(sfaq.releasedAt),
    rewrite: sfaq.rewrite,
    systemId: sfaq.systemId,
    title: sfaq.title
  }
}

</script>

<style scoped lang="scss">
.system-content-item {
  padding-bottom: 60px;
  .header {
    min-height: 36px;
    .border {
      width: 100%;
      height: 1px;
      border-bottom: 2px solid #e5e5e5;
      margin-top: 12px;
      margin-bottom: 24px;
    }
  }
  .el-form-item {
    margin-bottom: 15px;
  }
  .width-limit {
    min-width: 180px;
    max-width: 640px;
  }
}
.footfixed {
  position: fixed;
  z-index: 1000;
  bottom: 0;
  left: 220px;
  right: 0;
  background: #fff;
  padding: 15px 20px;
  border-top: 1px solid #eee;
  margin-bottom: 0 !important;
  text-align: right;
}
.changHgh /deep/ .el-input__inner {
  line-height: 1.3;
  padding-top: 4px;
  padding-bottom: 4px;
}
</style>
